package com.cloud.hotline.api.web;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.cloud.hotline.api.bean.HotlineImportForm;
import com.cloud.hotline.api.consts.HotLineConsts;
import com.cloud.hotline.api.entity.ToHotlineRevisitRecord;
import com.cloud.hotline.api.entity.ToHotlineStreetRecord;
import com.cloud.hotline.api.entity.ToHotlineUnitRecord;
import com.cloud.hotline.api.service.HotlineService;
import com.cloud.hotline.common.exception.BizException;
import com.cloud.hotline.common.result.Quokka;
import com.cloud.hotline.common.utils.ExcelHelper;
import com.cloud.hotline.common.utils.ValidationHelper;

@RestController
@RequestMapping("hotline/api/")
public class HotlineController {
	
	@Autowired
	public HotlineService hotlineService;

	/**
	 * 上传文件解析
	 * 
	 * @param file
	 *            文件
	 * @param type
	 *            当前上传文件类型 0： 诉求三率 1：街道承办 2： 部门承办
	 * @param reVisitType
	 *            回访类别 1：市级回访 2： 区级回访
	 * @param start
	 *            回访时段开始
	 * @param end
	 *            回访时段截止
	 * @return
	 * @throws IOException
	 */
	@PostMapping("analysis")
	public Quokka analysisXls(@RequestParam(value = "file", required = true) MultipartFile file, int type,
			int reVisitType, String start, String end) throws IOException {
		List<String> unitNames = hotlineService.listUnitNames();
		try {
			if (0 == type) {
				// 诉求三率
				if (1 == reVisitType) {
					// 市级回访
					List<ToHotlineRevisitRecord> records = ExcelHelper.xlsx2List(file.getInputStream(),
							HotLineConsts.FIELDS_REVISIT_RECORD, ToHotlineRevisitRecord.class);
					return new Quokka(true, ValidationHelper.validataCityRevisitRecord(records, start, end, unitNames));
				} else if (2 == reVisitType) {
					// 区级回访
					List<ToHotlineUnitRecord> records = ExcelHelper.xlsx2List(file.getInputStream(),
							HotLineConsts.FIELDS_UNIT_RECORD, ToHotlineUnitRecord.class, 0, 4); // 从模板上第0个sheet的第四行数据开始读
					return new Quokka(true, ValidationHelper.validateAreaRevisitRecord(records, start, end, unitNames));
				}
				return null;

			} else if (1 == type) {
				// 街道承办
				List<ToHotlineStreetRecord> records = ExcelHelper.xlsx2List(file.getInputStream(),
						HotLineConsts.FIELDS_STREET_RECORD, ToHotlineStreetRecord.class);
				return new Quokka(true, ValidationHelper.validateStreetUndertakeRecord(records, unitNames));
			} else {
				// 部门承办
				List<ToHotlineUnitRecord> records = ExcelHelper.xlsx2List(file.getInputStream(),
						HotLineConsts.FIELDS_UNIT_RECORD, ToHotlineUnitRecord.class, 0, 4);// 从模板上第0个sheet的第四行数据开始读
				return new Quokka(true, ValidationHelper.validateUnitUndertakeRecord(records, start, end, unitNames));
			}
		} catch (Exception e) {
			throw new BizException("文件解析失败，请检查模板是否正确");
		}
	}

	/**
	 * 数据集入库
	 * 
	 * @param records
	 * @return
	 */
	@PostMapping("import")
	public Quokka importData(@RequestBody HotlineImportForm records) {
		hotlineService.importData(records);
		return new Quokka(true);
	}

	/**
	 * 错误数据导出
	 * 
	 * @param records
	 * @return
	 */
	@PostMapping("exporterror")
	public ResponseEntity<byte[]> exportErrorData(@RequestBody HotlineImportForm records) {
		OutputStream o = null;
		try {
			if (records.getRevisitRecords().size() > 0) {
				// 诉求三率：市级回访
				o = ExcelHelper.list2Xlsx(records.getRevisitRecords(), "诉求三率（市级回访）问题数据", "",
						HotLineConsts.HEADERS_REVISIT_RECORD, ToHotlineRevisitRecord.class);
			} else if (records.getStreetRecords().size() > 0) {
				// 街道承办
				o = ExcelHelper.list2Xlsx(records.getStreetRecords(), "街道承办问题数据", "",
						HotLineConsts.HEADERS_STREET_RECORD, ToHotlineStreetRecord.class);
			} else if (records.getUnitRecords().size() > 0) {
				List<ToHotlineUnitRecord> unitRecords = records.getUnitRecords();
				if (records.getType() == 1) {
					// 诉求三率 ：区级回访
					o = ExcelHelper.list2Xlsx(unitRecords, "诉求三率（区级回访）问题数据", "", HotLineConsts.HEADERS_UNIT_RECORD,
							ToHotlineUnitRecord.class);
				} else {
					// 部门承办
					o = ExcelHelper.list2Xlsx(unitRecords, "部门承办问题数据", "", HotLineConsts.HEADERS_UNIT_RECORD,
							ToHotlineUnitRecord.class);
				}
			}
			HttpHeaders headers = new HttpHeaders();
			headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
			headers.add("Content-Disposition",
					"attachment;filename=" + new String("问题数据.xlsx".getBytes("ISO8859-1"), "UTF-8"));
			return new ResponseEntity<byte[]>(((ByteArrayOutputStream) o).toByteArray(), headers, HttpStatus.OK);
		} catch (Exception e) {
			throw new RuntimeException("文件生成失败，请稍候重试...", e);
		} finally {
			try {
				o.close();
			} catch (Exception e2) {
			}
		}
	}

}
